//
//  NSObject+Extension.swift
//  Weibo8023
//
//  Created by styshy on 15/12/9.
//  Copyright © 2015年 sz. All rights reserved.
//

import Foundation

extension NSObject{
    // 获取对象的所有属性
    func getProperties(clazz:AnyClass) -> [String]{
        // 存储对象属性个数
        var outCount:UInt32 = 0
        
        let ivars:UnsafeMutablePointer =  class_copyIvarList(clazz, &outCount)
        
        var propertyNames = [String]()
        
        for var i = 0;i < Int(outCount); i++ {
            let ivar:Ivar = ivars[i]
            let ivarName = ivar_getName(ivar)
            let pName = NSString(UTF8String: ivarName) as! String
            propertyNames.append(pName)
        }
        return propertyNames
    }
    
    // 对象的描述
    func descriptionFromClazz(clazz:AnyClass) -> String{
        let keys = getProperties(clazz)
        return (dictionaryWithValuesForKeys(keys) as NSDictionary).description
    }
    
    /// 归档
    ///
    /// - parameter obj:   对象
    /// - parameter coder: coder
    func encodeObj(obj:AnyObject, coder:NSCoder){
        let properties = obj.getProperties(obj.classForCoder)
        for p in properties{
            coder.encodeObject(obj.valueForKey(p), forKey: p)
        }
    }
    /// 解档
    ///
    /// - parameter obj:   对象
    /// - parameter coder: coder
    func decodeObj(obj:AnyObject,coder:NSCoder){
        let properties = obj.getProperties(obj.classForCoder)
        for p in properties{
            if let value = coder.decodeObjectForKey(p){
                obj.setValue(value, forKey:p)
            }
        }
    }
}